package com.huazi.oss.service;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.huazi.oss.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/**
 * @author shkstart
 * @create 2021-03-16 14:24
 */
@Service
public class OssServiceImpl implements OssService {
    //上传头像
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        //四个属性
        String endPoint = ConstantPropertiesUtils.END_POINT;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;
        String keyId = ConstantPropertiesUtils.KEY_ID;
        String keySecret = ConstantPropertiesUtils.KEY_SECRET;
        try{
            //  创建OSS实例对象
            OSS ossClient=new OSSClientBuilder().build(endPoint,keyId,keySecret);
            //获取上传文件的输入流
            InputStream inputStream=file.getInputStream();
            //获取文件名称
            String filename = file.getOriginalFilename();

            //获取一个随机id
            String substring = UUID.randomUUID().toString().substring(1, 5);
            filename=substring+filename;
            //获取当前日期
            String string = new DateTime().toString("yyyy/MM/dd");
            filename=string+"/"+filename;
            //调用oss方法实现上传
            ossClient.putObject(bucketName,filename,inputStream);
            //关闭OSSClient
            ossClient.shutdown();
            //拼接头像路径
            //https://huazi-edu-guli.oss-cn-guangzhou.aliyuncs.com/zaizai.jpg
            String url="https://"+bucketName+"."+endPoint+"/"+filename;
            System.out.println(url);
            return url;
        }catch (Exception e){
            return null;
        }

    }
}
